package Controller;

import DAOs.AdministrativeAssistantJpaController;
import DAOs.AdministratorJpaController;
import DAOs.CollaboratorJpaController;
import DAOs.exceptions.NonexistentEntityException;
import Entity.AdministrativeAssistant;
import Entity.Administrator;
import Entity.Collaborator;
import Entity.User;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author Esteban
 */
public class UsersController {

    private EntityManagerFactory emf;
    private EntityManager em;
    private AdministratorJpaController administratorsDao;
    private AdministrativeAssistantJpaController assistantsDao;
    private CollaboratorJpaController collaboratorDao;
    private String updateSucessfullMessage = "Informacion Actualizada";

    public UsersController(EntityManagerFactory emf) {
        administratorsDao = new AdministratorJpaController(emf);
        assistantsDao = new AdministrativeAssistantJpaController(emf);
        collaboratorDao = new CollaboratorJpaController(emf);
    }

    public void createUser(String name, String lastname, String username, String password, int cedula, String age, String role) {
        // line to encrypt the password
        password = BCrypt.hashpw(password, BCrypt.gensalt());
        if (role.equals("Administrador")) {
            Administrator administrator = new Administrator(name, lastname, username, password, cedula, age);
            administratorsDao.create(administrator);
        } else {
            if (role.equals("Asistente")) {
                AdministrativeAssistant assistant = new AdministrativeAssistant(name, lastname, username, password, cedula, age);
                assistantsDao.create(assistant);
            } else {
                if (role.equals("Colaborador")) {
                    Collaborator collaborator = new Collaborator(name, lastname, username, password, cedula, age);
                    collaboratorDao.create(collaborator);
                }
            }
        }
    }

    public void deleteUser(User usuario) {
        try {
            if (usuario == null) {
                JOptionPane.showMessageDialog(new JFrame(), "", "Error", JOptionPane.ERROR_MESSAGE);
            } else {
                if (usuario.getClass() == Administrator.class) {
                    administratorsDao.destroy(usuario.getId());
                } else {
                    if (usuario.getClass() == AdministrativeAssistant.class) {
                        assistantsDao.destroy(usuario.getId());
                    } else {
                        if (usuario.getClass() == Collaborator.class) {
                            collaboratorDao.destroy(usuario.getId());
                        }
                    }
                }
            }
        } catch (NonexistentEntityException ex) {
            Logger.getLogger(PeasantController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public ArrayList<User> findAllUsers() {
        ArrayList<User> usersList = new ArrayList<>();
        administratorsDao.findAdministratorEntities();
        assistantsDao.findAdministrativeAssistantEntities();
        collaboratorDao.findCollaboratorEntities();
        usersList.addAll(administratorsDao.findAdministratorEntities());
        usersList.addAll(assistantsDao.findAdministrativeAssistantEntities());
        usersList.addAll(collaboratorDao.findCollaboratorEntities());
        return usersList;
    }

    public ArrayList<User> findByName(String name) {
        ArrayList<User> usersList = findAllUsers();
        for (int i = 0; i < usersList.size(); i++) {
            if (!((usersList.get(i).getName() + usersList.get(i).getLastname()).contains(name))) {
                usersList.remove(i);
                i--;
            }
        }
        return usersList;
    }

    public ArrayList<User> findByCedula(int cedula) {
        ArrayList<User> usersList = findAllUsers();
        for (int i = 0; i < usersList.size(); i++) {
            if (!(usersList.get(i).getCedula() == cedula)) {
                usersList.remove(i);
                i--;
            }
        }
        return usersList;
    }
    
    public boolean Exist(int cedula){
        ArrayList<User> usersList = findAllUsers();
        for (int i = 0; i < usersList.size(); i++) {
            if (usersList.get(i).getCedula() == cedula) {
                return true;
            }
        }
        return false;
    }

    private void updateUser(User usuario, boolean updatedPassword) throws NonexistentEntityException, Exception {
        if (usuario == null) {
            JOptionPane.showMessageDialog(new JFrame(), "", "Error", JOptionPane.ERROR_MESSAGE);
        } else {
            if (updatedPassword) {
                usuario.setUserPassword(BCrypt.hashpw(usuario.getUserPassword(), BCrypt.gensalt()));
            }
            if (usuario.getClass() == Administrator.class) {
                administratorsDao.edit((Administrator) usuario);
            } else {
                if (usuario.getClass() == AdministrativeAssistant.class) {
                    assistantsDao.edit((AdministrativeAssistant) usuario);
                } else {
                    if (usuario.getClass() == Collaborator.class) {
                        collaboratorDao.edit((Collaborator) usuario);
                    }
                }
            }
        }
    }

    public User updateUser(User currentUser, int selectedRole, boolean updatedPassword) throws NonexistentEntityException, Exception {
        if ((currentUser.getClass().getSimpleName().equals("Administrator") && selectedRole == 0)
                || (currentUser.getClass().getSimpleName().equals("AdministrativeAssistant") && selectedRole == 1)
                || (currentUser.getClass().getSimpleName().equals("Collaborator") && selectedRole == 2)) {
            updateUser(currentUser, updatedPassword);
        } else {
            deleteUser(currentUser);
            if (selectedRole == 0) {
                currentUser = new Administrator(currentUser.getName(), currentUser.getLastname(), currentUser.getUserName(), currentUser.getUserPassword(), currentUser.getCedula(), currentUser.getAge());
                administratorsDao.create((Administrator) currentUser);
                List<Administrator> list = administratorsDao.findAdministratorEntities();
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getCedula() == currentUser.getCedula()) {
                        currentUser.setId(list.get(i).getId());
                    }
                }
            } else {
                if (selectedRole == 1) {
                    currentUser = new AdministrativeAssistant(currentUser.getName(), currentUser.getLastname(), currentUser.getUserName(), currentUser.getUserPassword(), currentUser.getCedula(), currentUser.getAge());
                    assistantsDao.create((AdministrativeAssistant) currentUser);
                    List<AdministrativeAssistant> list = assistantsDao.findAdministrativeAssistantEntities();
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(i).getCedula() == currentUser.getCedula()) {
                            currentUser.setId(list.get(i).getId());
                        }
                    }
                } else {
                    currentUser = new Collaborator(currentUser.getName(), currentUser.getLastname(), currentUser.getUserName(), currentUser.getUserPassword(), currentUser.getCedula(), currentUser.getAge());
                    collaboratorDao.create((Collaborator) currentUser);
                    List<Collaborator> list = collaboratorDao.findCollaboratorEntities();
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(i).getCedula() == currentUser.getCedula()) {
                            currentUser.setId(list.get(i).getId());
                        }
                    }
                }
            }
        }
        return currentUser;
    }
}
